// Copyright 2021 Guoyoko. All Rights Reserved.

#include "SWPlacePanelContainer.h"
#include "SWGameViewportClient.h"
#include "Styling/SlateBrush.h"
#include "Engine/StaticMesh.h"
#include "Engine/StaticMeshActor.h"
#include "Components/StaticMeshComponent.h"
#include "Style/SWCoreStyle.h"
#include "Engine/World.h"


void SSWPlacePanelContainer::Initialize()
{
	const FSlateBrush* TempSlateBrush = 
		FSlateStyleRegistry::FindSlateStyle(FCoreStyle::Get().GetStyleSetName())->GetOptionalBrush("WidgetReflector.Icon");

	PlaceListSource.AddUnique(MakeShareable(new FPlacePanelItem("Cube", FSWCoreStyle::Get().GetBrush("Placement.Cube"))));

	PlaceListSource.AddUnique(MakeShareable(new FPlacePanelItem("Sphere", FSWCoreStyle::Get().GetBrush("Placement.Sphere"))));
}

void SSWPlacePanelContainer::Construct(const FArguments& InArgs)
{
	Initialize();

	TSharedPtr<SWidget> PlacePanel;

	if(PlaceListSource.Num() > 0)
	{
		PlacePanel = 
			SNew(SListView<TSharedPtr<FPlacePanelItem>>)
			.ListItemsSource(&PlaceListSource)
			.OnGenerateRow(this, &SSWPlacePanelContainer::OnGenerateRowForList)
			.OnMouseButtonClick(this, &SSWPlacePanelContainer::OnPlacePanelItemClicked);
	}

	ChildSlot
		[
			PlacePanel.ToSharedRef()

		];

}

TSharedRef<ITableRow> SSWPlacePanelContainer::OnGenerateRowForList(TSharedPtr<FPlacePanelItem> InItem, const TSharedRef<STableViewBase>& OwnerTable)
{
	return 
		SNew(STableRow<TSharedPtr<FPlacePanelItem>>, OwnerTable)
		.Content()
		[
			SNew(SBox)
			.VAlign(VAlign_Center)
			.HAlign(HAlign_Left)
			[
				SNew(SHorizontalBox)
				+ SHorizontalBox::Slot()
				.VAlign(VAlign_Center)
				.HAlign(HAlign_Left)
				.AutoWidth()
				.Padding(2.f)
				[
					SNew(SImage)
					.Image(InItem->ItemIcon)
				]

				+ SHorizontalBox::Slot()
				.VAlign(VAlign_Center)
				.HAlign(HAlign_Left)
				.FillWidth(1.0)
				.Padding(10.f)
				[
					SNew(STextBlock)
					.Text(FText::FromName(InItem->ItemName))
				]
			]
		];

}

void SSWPlacePanelContainer::OnPlacePanelItemClicked(TSharedPtr<FPlacePanelItem> PlacePanelItem)
{
	if (GVC)
	{
		AStaticMeshActor* PlaceSMA = 
			GVC->GetWorld()->SpawnActor<AStaticMeshActor>(FVector::ZeroVector, FRotator::ZeroRotator);
		
		PlaceSMA->GetStaticMeshComponent()->SetMobility(EComponentMobility::Movable);

		if ("Cube" == PlacePanelItem->ItemName)
		{
			UStaticMesh* SM = Cast<UStaticMesh>(StaticLoadObject(UStaticMesh::StaticClass(), NULL, TEXT("/Engine/BasicShapes/Cube")));
			PlaceSMA->GetStaticMeshComponent()->SetStaticMesh(SM);
			PlaceSMA->Tags.AddUnique("Cube");
		}
		else if ("Sphere" == PlacePanelItem->ItemName)
		{
			UStaticMesh* SM = Cast<UStaticMesh>(StaticLoadObject(UStaticMesh::StaticClass(), NULL, TEXT("/Engine/BasicShapes/Sphere")));
			PlaceSMA->GetStaticMeshComponent()->SetStaticMesh(SM);
			PlaceSMA->Tags.AddUnique("Sphere");
		}
		
		GVC->PlaceActor(PlaceSMA);
	}
}

